package cn.zooz.common.util.inteceptor;

/**
 * Created by Bradish7Y on 16/12/28.
 */

import cn.zooz.common.util.annotation.Token;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * Created by Bradish7Y on 15/8/14.
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    private final static String INPUT_TOKEN = "token";
    private final static String TOKEN = INPUT_TOKEN + "_";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Token token = method.getAnnotation(Token.class);

            if (token != null) {
                boolean save = token.save();
                String key = TOKEN + token.key();
                if (save) {
                    String tokenStr = UUID.randomUUID().toString();
                    request.getSession(true).setAttribute(key, tokenStr);
                    //redis.set(key, tokenStr);
                }

                boolean remove = token.remove();
                if (remove) {
                    if (isDuplicatedSubmit(request, key)) {
                        response.sendRedirect("/error/111");
                        //request.getRequestDispatcher("/WEB-INF/views/form.jsp").forward(request, response);
                        return false;
                    } else {
                        request.getSession(false).removeAttribute(key);
                    }
                }
            }

            return super.preHandle(request, response, handler);
        } else {
            return super.preHandle(request, response, handler);
        }

    }

    private boolean isDuplicatedSubmit(HttpServletRequest request, String key) {
        String sessionToken = (String) request.getSession(false).getAttribute(key);
        if (sessionToken == null) {
            return true;
        }

        String formToken = request.getParameter(INPUT_TOKEN);
        if (formToken == null) {
            return true;
        }

        if (!sessionToken.equals(formToken)) {
            return true;
        }
        return false;
    }
}

